package com.xuzhiguang.lightnat.client.control.handler;

import com.xuzhiguang.lightnat.common.manager.ControlChannelManager;
import com.xuzhiguang.lightnat.client.control.ControlClientHolder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;

@Slf4j
@ChannelHandler.Sharable
public class InactiveHandler extends ChannelInboundHandlerAdapter {

    private final Timer timer = new Timer("c-reconnect-timer", true);

    private final static long MAX_DELAY_TIME = 10 * 60 * 1000;

    private final static long DEFAULT_DELAY_TIME = 3 * 1000;

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        log.debug("control channel inactive. channel:{}", ctx.channel());

        Boolean authed = ControlChannelManager.getAuthed(ctx.channel());
        if (authed != null && authed) {
            reconnectControlClient(DEFAULT_DELAY_TIME);
        }

        super.channelInactive(ctx);
    }

    private void reconnectControlClient(long delay) {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                boolean success = false;
                try {
                    success = ControlClientHolder.get().connect();
                } catch (Exception ignored) {

                }

                if (!success) {
                    log.info("control reconnect fail.");
                    reconnectControlClient(Math.min(delay * 2, MAX_DELAY_TIME));
                } else {
                    log.info("control reconnect success.");
                }
            }
        }, delay);
    }
}
